package com.aaa.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/*
* Spring Security配置类
*
* */
//当前类是个配置类
@Configuration
//使用security配置
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled = true,jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //配置静态资源
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略 匹配mvc 可以访问
        web.ignoring().mvcMatchers("/css/*","/fonts/*","/images/*","/lib/layui/css/*","/js/*");
    }

    //用户信息
    @Resource
    UserDetailsServiceImpl userDetailsService;
    //登录成功处理
    @Resource
    SuccessHandler successHandler;
    @Resource
    FailureHandler failureHandlerl;
    @Resource
    DeniedHandler deniedHandler;
    @Resource
    EntryPointHandler entryPointHandler;
    @Resource
    JwtAuthenticationFilter jwtAuthenticationFilter;
    /*
    * 1.是否登录;
    * 2.认证
    * a。校验用户身份是否正确
    * b.
    * */
    /*
    * http请求处理配置
    *
    * */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权请求


        http
                // 授权请求
              //  .authorizeRequests()
                // 所有请求
          //      .anyRequest()
                // 已认证
              //  .authenticated() // 所有请求必须经过身份认证(登录)之后才能授权访问
              //  .and()
                .headers().frameOptions().sameOrigin()//表示页面可以在frame 中展示。
                .and()
                // 配置form表单进行登录
                .formLogin()
                // 登录页面
              //  .loginPage("/login.html")
                // 用户名参数:security默认表单提交时用户名叫username
                .usernameParameter("eusername")
                // 密码参数:security默认表单提交时用户名叫password
                .passwordParameter("epass")
                // 登录验证路径:form表单的提交路径,默认提交路径/login
                .loginProcessingUrl("/login-check")
                // 默认成功路径
              //  .defaultSuccessUrl("/index.html")
                // 失败访问路径
             //   .failureUrl("/user/error")
                .successHandler(successHandler)
                .failureHandler(failureHandlerl)
                // 允许访问
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                // 允许访问判断:调用方法，使用方法得返回结果做判断，是否可以访问
                .access("@rbacConfig.hasPermission(authentication,request)")
                .and()
                //异常处理器
                .exceptionHandling()
                //访问被拒绝
                .accessDeniedHandler(deniedHandler)
                .authenticationEntryPoint(entryPointHandler)
                .and()
                .cors()//运行cors请求
                .and()
                // 跨域请求
                .csrf()
                // 禁用
                .disable();
        //在Security判断是否认证之前,先拦截请求,判断是否携带tokne
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
    /**
     * 认证配置
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication()
                // 密码编译器
                 .passwordEncoder(new MyPasswordEncoder())
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zs").password("$2a$10$DBacW9/x7vkWD8iktmDQeO/XGJuoGH7Kboina5rcW1A13s2p5dVdO").authorities("ROLE_ADMIN");*/
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
        //System.out.println(userDetailsService.loadUserByUsername("yyx"));

    }
}
